package com.jg.framework.utils.sys;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Properties;

public class SystemUtil {

	private static SystemUtil currentSystem = null;
	private InetAddress localHost = null;

	private SystemUtil() {
		try {
			localHost = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 单例模式获取对象
	 * 
	 * @return
	 */
	public static SystemUtil getInstance() {
		if (currentSystem == null)
			currentSystem = new SystemUtil();
		return currentSystem;
	}

	/**
	 * 本地IP
	 * 
	 * @return IP地址
	 */
	public String getIP() {
		String ip = getLocalIP();
		return ip;
	}

	/**
	 * 获取用户机器名称
	 * 
	 * @return
	 */
	public String getHostName() {
		return localHost.getHostName();
	}

	/** 
     * 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux 等. 
     */  
    public static String getOSName() {  
        return System.getProperty("os.name").toLowerCase();  
    }
    
	/**
	 * 获取Mac地址
	 * 
	 * @return Mac地址，例如：F0-4D-A2-39-24-A6
	 */
	public String getMac() {
		if(isWindowsOS()){
			NetworkInterface byInetAddress;
			try {
				byInetAddress = NetworkInterface.getByInetAddress(localHost);
				byte[] hardwareAddress = byInetAddress.getHardwareAddress();
				return getMacFromBytes(hardwareAddress);
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			return getUnixMACAddress();
		}
		return null;
	}

	/**
	 * 获取当前系统名称
	 * 
	 * @return 当前系统名，例如： windows xp
	 */
	public String getSystemName() {
		Properties sysProperty = System.getProperties();
		// 系统名称
		String systemName = sysProperty.getProperty("os.name");
		return systemName;
	}

	private String getMacFromBytes(byte[] bytes) {
		StringBuffer mac = new StringBuffer();
		byte currentByte;
		boolean first = false;
		for (byte b : bytes) {
			if (first) {
				mac.append("-");
			}
			currentByte = (byte) ((b & 240) >> 4);
			mac.append(Integer.toHexString(currentByte));
			currentByte = (byte) (b & 15);
			mac.append(Integer.toHexString(currentByte));
			first = true;
		}
		return mac.toString().toUpperCase();
	}
	
	public String getUnixMACAddress() {  
        String mac = null;  
        BufferedReader bufferedReader = null;  
        Process process = null;  
        try {  
            // linux下的命令，一般取eth0作为本地主网卡  
            process = Runtime.getRuntime().exec("ifconfig eth0");  
            // 显示信息中包含有mac地址信息  
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));  
            String line = null;  
            int index = -1;  
            while ((line = bufferedReader.readLine()) != null) {  
                // 寻找标示字符串[hwaddr]  
                index = line.toLowerCase().indexOf("hwaddr");  
                if (index >= 0) {// 找到了  
                    // 取出mac地址并去除2边空格  
                    mac = line.substring(index + "hwaddr".length() + 1).trim();  
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace(); 
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {  
                e1.printStackTrace();  
            }  
            bufferedReader = null;  
            process = null;  
        }  
        return mac;
    }
	
	/**
	  * 获得主机IP
	  *
	  * @return String
	  */
	public static boolean isWindowsOS(){
		boolean isWindowsOS = false;
		String osName = System.getProperty("os.name");
		if(osName.toLowerCase().indexOf("windows")>-1){
			isWindowsOS = true;
		}
		return isWindowsOS;
	}

	  /**
	    * 获取本机ip地址，并自动区分Windows还是linux操作系统
	    * @return String
	    */
	public static String getLocalIP(){
		String sIP = "";
		InetAddress ip = null;
		try {
			// 如果是Windows操作系统
			if (isWindowsOS()) {
				ip = InetAddress.getLocalHost();
			}
			// 如果是Linux操作系统
			else {
				boolean bFindIP = false;
				Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
						.getNetworkInterfaces();
				while (netInterfaces.hasMoreElements()) {
					if (bFindIP) {
						break;
					}
					NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
					// ----------特定情况，可以考虑用ni.getName判断
					// 遍历所有ip
					Enumeration<InetAddress> ips = ni.getInetAddresses();
					while (ips.hasMoreElements()) {
						ip = (InetAddress) ips.nextElement();
						if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() // 127.开头的都是lookback地址
								&& ip.getHostAddress().indexOf(":") == -1) {
							bFindIP = true;
							break;
						}
					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (null != ip) {
			sIP = ip.getHostAddress();
		}
		return sIP;
	}

	public static void main(String[] args) {
		System.out.println(SystemUtil.getInstance().getIP());
		System.out.println(SystemUtil.getInstance().getMac());
	}
}
